package nio;

import java.io.IOException;
import java.nio.file.*;

/**
 * Created by Administrator on 2017/10/22 022.
 */
public class WatchServiceDemo
{
    public static void main(String[] args)
    {
        try
        {
            WatchService service = FileSystems.getDefault().newWatchService();
            Path path = Paths.get("C:");
            path.register(service,
                    StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE
                    );
            System.out.println("开始监听" + path.getRoot() + "的变化");
            while (true)
            {
                WatchKey key = service.take();
                for(WatchEvent<?> wa : key.pollEvents())
                {
                    System.out.println("监听到文件变化，文件为 " + wa.context() + "  变化类型为" + wa.kind());
                }
                boolean isValid = key.reset();
                if(!isValid)
                    break;
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }catch (InterruptedException e2)
        {
            System.out.println("take被打断");
        }
    }
}
